package com.kstech.mp3604.utils

import android.annotation.SuppressLint
import android.content.Context.CONNECTIVITY_SERVICE
import android.content.Context.WIFI_SERVICE
import android.net.ConnectivityManager
import android.net.ConnectivityManager.TYPE_WIFI
import android.net.wifi.WifiManager
import com.kstech.mp3604.base.MyApplication
import java.net.Inet4Address
import java.net.NetworkInterface


object IPUtil {
    fun getLocalIpAddress(): String {
        val netManager =
            MyApplication.app.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
        val info = netManager.activeNetworkInfo

        if (info != null && info.isConnected) {
            if (info.type == TYPE_WIFI) {
                return getWifiIpAddress()
            } else {
                return getEthIpAddress()
            }
        }
        return "0.0.0.0"


    }


    // 获取wifi的ip地址
    @SuppressLint("DefaultLocale")
    private fun getWifiIpAddress(): String {
        val wifiManager = MyApplication.app.getSystemService(WIFI_SERVICE) as WifiManager
        val wifiInfo = wifiManager.connectionInfo

        // 获取32位整型IP地址
        val ipAddress = wifiInfo.getIpAddress()

        //返回整型地址转换成“*.*.*.*”地址
        return String.format(
            "%d.%d.%d.%d",
            ipAddress and 0xff,
            ipAddress shr 8 and 0xff,
            ipAddress shr 16 and 0xff,
            ipAddress shr 24 and 0xff
        )
    }

    // 获取有线网络的ip4地址
    private fun getEthIpAddress(): String {
        val infaceName = "eth0"
        val ip = "0.0.0.0"
        try {
            val netInterface = NetworkInterface.getNetworkInterfaces()
            while (netInterface.hasMoreElements()) {
                val inface = netInterface.nextElement()
                if (!inface.isUp()) {
                    continue
                }

                // eth0 有线网络判断
                if (infaceName != inface.displayName) {
                    continue
                }
                val netAddressList = inface.getInetAddresses()
                while (netAddressList.hasMoreElements()) {
                    val inetAddress = netAddressList.nextElement()
                    // 获取IP4地址
                    if (inetAddress is Inet4Address) {
                        return inetAddress.getHostAddress()
                    }
                }
            }
        } catch (e: Exception) {
        }
        return ip
    }


}